//
//  PermissionProvider.swift
//  permission
//
//  Created by Mr.wang on 2018/12/10.
//  Copyright © 2018 Mr.wang. All rights reserved.
//

import UIKit

struct PermissionProvider {
    
    static func request(_ types: [PermissionType],
                        success: @escaping () -> (),
                        failure: @escaping () -> () = {}) {
        guard types.count > 0 else {
            DispatchQueue.main.async {
                success()
            }
            return
        }
        
        request(types[0], success: {
            var newTypes = types
            newTypes.remove(at: 0)
            request(newTypes, success: success, failure: failure)
        }, failure: failure)
    }
    
    static func request(_ type: PermissionType,
                        success: @escaping () -> (),
                        failure: @escaping () -> () = {}) {
        type.permission.requestPermission { _ in
            switch type.permission.status {
            case .authorized:
                DispatchQueue.main.async {
                    success()
                }
            case .denied:
                var message = "Please allow AE Solar access to your \(type.displayText) in the iPhone Settings"
                if UIDevice.current.isZhHans {
                    message = "请在iPhone的“设置”中，允许AE Solar访问你的\(type.displayText)"
                }
                showAlert(message, clusure: failure)
                break
            case .disabled:
                var message = "\(type.displayText) is not available"
                if UIDevice.current.isZhHans {
                    message = "\(type.displayText)当前不可用。"
                }
                showAlert(message, clusure: failure)
                break
            default:
                break
            }
        }
    }
    
    static func showAlert(_ title: String, clusure: @escaping () -> ()) {
        DispatchQueue.main.async {
            let alert = UIAlertController.init(title: "系统提示".localized, message: title, preferredStyle: .alert)
            alert.addAction(UIAlertAction.init(title: "取消".localized, style: .cancel, handler: { (_) in
                clusure()
            }))
            alert.addAction(UIAlertAction.init(title: "设置".localized, style: .default, handler: { (_) in
                clusure()
                guard let url = URL.init(string: UIApplication.openSettingsURLString) else { return }
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }))
            UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
        }
    }
    
}
